// pages/main/workorder/workorder-detail/workorder-detail.js
Page({
  data: {
    workorderId: null,
    source: '', // 来源：apply-record, process-workorder, process-record
    workorder: null,
    loading: true,
    error: false,
    errorMessage: '',
    isApplicant: false, // 是否是申请人
    isHandler: false, // 是否是处理人
    canAccept: false, // 是否可以接单
    canComplete: false, // 是否可以完成
    canCancel: false, // 是否可以取消
    canFinishFromRecord: false, // 处理中列表进入是否可结束
    showFinishDialog: false,
    finishStatus: 'resolved',
    finishRemark: '',
    finishSubmitting: false
  },

  onLoad(options) {
    const workorderId = options.id;
    const source = options.source || 'apply-record'; // 来源页面
    
    this.setData({
      workorderId: workorderId,
      source: source
    });

    // 加载工单详情
    this.loadWorkorderDetail();
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadWorkorderDetail();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  },

  // 加载工单详情
  loadWorkorderDetail() {
    const username = wx.getStorageSync('username') || '';
    
    // 从上一个页面获取工单数据
    const pages = getCurrentPages();
    const prevPage = pages[pages.length - 2];
    
    let workorder = null;
    if (prevPage && prevPage.data) {
      // 尝试从上一个页面获取工单数据
      const allWorkorders = prevPage.data.workorders || 
                           prevPage.data.records || 
                           prevPage.data.filteredWorkorders || 
                           prevPage.data.filteredRecords ||
                           prevPage.data.pendingWorkorders ||
                           prevPage.data.processingWorkorders || [];
      workorder = allWorkorders.find(w => w.id == this.data.workorderId || w.id == parseInt(this.data.workorderId));
    }

    if (!workorder) {
      // 如果找不到，使用模拟数据
      workorder = {
        id: this.data.workorderId,
        workorder_number: 'GD202412011200001234',
        workorder_type: 'hardware',
        type_name: '硬件',
        content: '电脑无法开机，需要检查硬件问题',
        location: '3楼办公室301',
        appointment_date: '2024-12-02',
        appointment_time: '14:00',
        username: username,
        handler: '',
        status: 'pending',
        status_text: '待处理',
        create_time: '2024-12-01 12:00:00',
        update_time: '2024-12-01 12:00:00',
        images: []
      };
    }

    // 判断用户角色和权限
    const isApplicant = workorder.username === username;
    const isHandler = workorder.handler && workorder.handler === username;
    
    // 确保status是字符串类型进行比较
    const workorderStatus = String(workorder.status || '').toLowerCase();
    const source = String(this.data.source || '');
    
    const canAccept = source === 'process-workorder' && workorderStatus === 'pending';
    const canComplete = source === 'process-workorder' && workorderStatus === 'processing';
    const canCancel = source === 'process-workorder' && workorderStatus === 'processing' && isHandler;
    // 从处理记录进入的处理中工单，显示处理完成按钮
    const canFinishFromRecord = (source === 'process-record' || source === 'process-workorder') && workorderStatus === 'processing';

    console.log('工单详情加载:', {
      source: source,
      workorderStatus: workorderStatus,
      username: username,
      handler: workorder.handler,
      isHandler: isHandler,
      canAccept: canAccept,
      canComplete: canComplete,
      canCancel: canCancel,
      canFinishFromRecord: canFinishFromRecord
    });

    this.setData({
      workorder: workorder,
      isApplicant: isApplicant,
      isHandler: isHandler,
      canAccept: Boolean(canAccept),  // 确保是布尔值
      canComplete: Boolean(canComplete),  // 确保是布尔值
      canCancel: Boolean(canCancel),  // 确保是布尔值
      canFinishFromRecord: Boolean(canFinishFromRecord),  // 确保是布尔值
      loading: false,
      error: false,
      errorMessage: ''
    });
  },

  // 接单处理
  onAccept() {
    wx.showModal({
      title: '确认接单',
      content: '确定要接单处理此工单吗？',
      success: (res) => {
        if (res.confirm) {
          this.acceptWorkorder();
        }
      }
    });
  },

  // 接单处理
  acceptWorkorder() {
    wx.showLoading({ title: '处理中...' });
    
    const username = wx.getStorageSync('username') || '';
    
    // TODO: 调用后端API接单
    // 模拟API调用
    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({
        title: '接单成功',
        icon: 'success',
        duration: 1500
      });
      
      const now = new Date();
      // 更新工单状态
      this.setData({
        'workorder.status': 'processing',
        'workorder.status_text': '处理中',
        'workorder.handler': username,
        'workorder.update_time': this.formatDateTime(now),
        'workorder.accept_time': this.formatDateTime(now),
        canAccept: false,
        canComplete: true,
        canCancel: true,
        isHandler: true
      });
      
      // 通知上一页刷新
      this.refreshPrevPage();
    }, 1000);
  },

  // 完成工单
  onComplete() {
    wx.showModal({
      title: '确认完成',
      content: '确定要完成此工单吗？',
      success: (res) => {
        if (res.confirm) {
          this.completeWorkorder();
        }
      }
    });
  },

  // 完成工单
  completeWorkorder() {
    wx.showLoading({ title: '处理中...' });
    
    const now = new Date();
    // TODO: 调用后端API完成工单
    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({
        title: '工单已完成',
        icon: 'success',
        duration: 1500
      });
      
      // 更新工单状态
      this.setData({
        'workorder.status': 'completed',
        'workorder.status_text': '已完成',
        'workorder.update_time': this.formatDateTime(now),
        'workorder.complete_time': this.formatDateTime(now),
        'workorder.finish_result': '问题已解决',
        canComplete: false,
        canCancel: false,
        canFinishFromRecord: false
      });
      
      // 通知上一页刷新
      this.refreshPrevPage();
    }, 1000);
  },

  // 取消处理
  onCancel() {
    wx.showModal({
      title: '确认取消',
      content: '确定要取消处理此工单吗？',
      success: (res) => {
        if (res.confirm) {
          this.cancelProcess();
        }
      }
    });
  },

  // 取消处理
  cancelProcess() {
    wx.showLoading({ title: '处理中...' });
    
    // TODO: 调用后端API取消处理
    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({
        title: '已取消处理',
        icon: 'success',
        duration: 1500
      });
      
      // 更新工单状态
      this.setData({
        'workorder.status': 'pending',
        'workorder.status_text': '待处理',
        'workorder.handler': '',
        'workorder.update_time': this.formatDateTime(new Date()),
        canAccept: true,
        canComplete: false,
        canCancel: false,
        canFinishFromRecord: false,
        isHandler: false
      });
      
      // 通知上一页刷新
      this.refreshPrevPage();
    }, 1000);
  },

  // 预览图片
  onImageTap(e) {
    const index = e.currentTarget.dataset.index;
    const images = this.data.workorder.images || [];
    
    wx.previewImage({
      current: images[index],
      urls: images
    });
  },

  // 刷新上一页
  refreshPrevPage() {
    const pages = getCurrentPages();
    const prevPage = pages[pages.length - 2];
    if (prevPage && typeof prevPage.loadWorkorders === 'function') {
      prevPage.loadWorkorders();
    } else if (prevPage && typeof prevPage.loadRecords === 'function') {
      prevPage.loadRecords();
    }
  },

  // 处理记录-处理完成
  onFinishProcessTap() {
    this.setData({
      showFinishDialog: true,
      finishStatus: 'resolved',
      finishRemark: ''
    });
  },

  onFinishStatusChange(e) {
    const value = e.detail.value || 'resolved';
    this.setData({ finishStatus: value });
  },

  onFinishRemarkInput(e) {
    this.setData({ finishRemark: e.detail.value || '' });
  },

  onFinishDialogClose() {
    if (this.data.finishSubmitting) {
      return;
    }
    this.setData({
      showFinishDialog: false,
      finishRemark: ''
    });
  },

  submitFinishResult() {
    if (this.data.finishSubmitting) {
      return;
    }

    const remark = (this.data.finishRemark || '').trim();
    if (!remark) {
      wx.showToast({
        title: '请填写备注说明',
        icon: 'none'
      });
      return;
    }

    this.setData({ finishSubmitting: true });
    wx.showLoading({ title: '提交中...' });

    // TODO: 调用后端API提交处理结果
    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({
        title: '提交成功',
        icon: 'success'
      });

      const isResolved = this.data.finishStatus === 'resolved';
      const statusText = isResolved ? '已完成' : '问题未解决';
      const now = new Date();
      
      // 构建更新数据
      const updateData = {
        finishSubmitting: false,
        showFinishDialog: false,
        canFinishFromRecord: false,
        finishRemark: '',
        'workorder.status': isResolved ? 'completed' : 'processing',
        'workorder.status_text': statusText,
        'workorder.finish_result': isResolved ? '问题已解决' : '问题未解决',
        'workorder.finish_remark': remark,
        'workorder.update_time': this.formatDateTime(now)
      };
      
      // 只有问题已解决时才记录完成时间
      if (isResolved) {
        updateData['workorder.complete_time'] = this.formatDateTime(now);
      }

      this.setData(updateData);

      this.refreshPrevPage();
    }, 1000);
  },

  // 重试加载
  onRetry() {
    this.setData({
      error: false,
      errorMessage: '',
      loading: true
    });
    this.loadWorkorderDetail();
  },

  // 格式化日期时间
  formatDateTime(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hour = String(date.getHours()).padStart(2, '0');
    const minute = String(date.getMinutes()).padStart(2, '0');
    const second = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
  }
});

